﻿<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>供应商管理</h2>
      <button @click="openAdd" class="btn-primary">新增供应商</button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-panel">
      <div class="search-form">
        <div class="form-group">
          <label>关键词</label>
          <input 
            v-model="query.keyword" 
            @keyup.enter="search" 
            placeholder="供应商名称" 
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>状态</label>
          <select v-model="query.status" class="form-select">
            <option value="">全部</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <button @click="search" class="btn-primary">搜索</button>
        <button @click="reset" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-panel">
      <div class="panel-header">
        <h3>供应商列表</h3>
        <p>管理所有供应商信息</p>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="list.length === 0" class="empty">
        暂无数据
      </div>
      
      <div v-else class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>供应商编码</th>
              <th>供应商名称</th>
              <th>联系人</th>
              <th>电话</th>
              <th>邮箱</th>
              <th>地址</th>
              <th>付款期限</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id">
              <td>{{ item.supplierCode || '-' }}</td>
              <td>{{ item.supplierName || '-' }}</td>
              <td>{{ item.contactName || '-' }}</td>
              <td>{{ item.phone || '-' }}</td>
              <td>{{ item.email || '-' }}</td>
              <td class="address-cell" :title="item.address">{{ item.address || '-' }}</td>
              <td>{{ item.paymentTermDays || 0 }}天</td>
              <td>
                <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
              </td>
              <td>{{ formatDate(item.createdAt) }}</td>
              <td class="action-cell">
                <button @click="openEdit(item)" class="btn-edit">编辑</button>
                <button @click="remove(item)" class="btn-delete">删除</button>
                <button @click="openProducts(item)" class="btn-secondary">产品</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="pageNum === 1" class="btn-page">上一页</button>
      <span class="page-info">
        第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，总计 {{ total }} 条
      </span>
      <button @click="nextPage" :disabled="pageNum * pageSize >= total" class="btn-page">下一页</button>
    </div>

    <!-- 新增/编辑对话框 -->
    <div v-if="showDialog" class="modal-overlay" @click="closeDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ dialogType === 'add' ? '新增供应商' : '编辑供应商' }}</h3>
          <button @click="closeDialog" class="btn-close"></button>
        </div>
        
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-group">
              <label>供应商编码 *</label>
              <input 
                v-model="form.supplierCode" 
                :disabled="dialogType === 'edit'"
                placeholder="请输入供应商编码" 
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>供应商名称 *</label>
              <input 
                v-model="form.supplierName" 
                placeholder="请输入供应商名称" 
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>联系人</label>
              <input 
                v-model="form.contactName" 
                placeholder="请输入联系人" 
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>电话</label>
              <input 
                v-model="form.phone" 
                placeholder="请输入电话" 
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input 
                v-model="form.email" 
                placeholder="请输入邮箱" 
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>付款期限(天)</label>
              <input 
                v-model.number="form.paymentTermDays" 
                type="number" 
                placeholder="请输入付款期限" 
                class="form-input"
              />
            </div>
            <div class="form-group full-width">
              <label>地址</label>
              <textarea 
                v-model="form.address" 
                placeholder="请输入地址" 
                class="form-textarea"
              ></textarea>
            </div>
            <div class="form-group">
              <label>状态 *</label>
              <select v-model="form.status" class="form-select">
                <option value="1">启用</option>
                <option value="0">禁用</option>
              </select>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeDialog" class="btn-secondary">取消</button>
          <button @click="submit" class="btn-primary">确定</button>
        </div>
      </div>
    </div>

    <!-- 产品管理对话框 -->
    <div v-if="showProductsPanel" class="modal-overlay" @click="closeProducts">
      <div class="modal-content products-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ currentSupplier?.supplierName }} - 产品管理</h3>
          <button @click="closeProducts" class="btn-close"></button>
        </div>
        
        <div class="modal-body">
          <div class="products-header">
            <h4>已绑定产品</h4>
            <button @click="openBindProducts" class="btn-primary">绑定新产品</button>
          </div>
          
          <div v-if="products.length === 0" class="empty">
            暂无绑定产品
          </div>
          
          <div v-else class="products-table">
            <table class="data-table">
              <thead>
                <tr>
                  <th>产品编码</th>
                  <th>产品名称</th>
                  <th>规格型号</th>
                  <th>分类</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="product in products" :key="product.id">
                  <td>{{ product.spuCode || '-' }}</td>
                  <td>{{ product.productName || '-' }}</td>
                  <td>{{ product.specification || '-' }}</td>
                  <td>{{ product.categoryName || '-' }}</td>
                  <td>
                    <button @click="unbindProduct(product)" class="btn-delete">解绑</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 绑定产品对话框 -->
    <div v-if="showBindPanel" class="modal-overlay" @click="closeBind">
      <div class="modal-content bind-modal" @click.stop>
        <div class="modal-header">
          <h3>绑定产品</h3>
          <button @click="closeBind" class="btn-close"></button>
        </div>
        
        <div class="modal-body">
          <div class="bind-search">
            <div class="form-group">
              <label>产品名称</label>
              <input 
                v-model="bindQuery.keyword" 
                @keyup.enter="loadBindList" 
                placeholder="请输入产品名称" 
                class="form-input"
              />
            </div>
            <button @click="loadBindList" class="btn-primary">搜索</button>
          </div>
          
          <div v-if="bindList.length === 0" class="empty">
            暂无数据
          </div>
          
          <div v-else class="bind-table">
            <table class="data-table">
              <thead>
                <tr>
                  <th>
                    <input type="checkbox" @change="toggleAll" />
                  </th>
                  <th>产品编码</th>
                  <th>产品名称</th>
                  <th>规格型号</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in bindList" :key="item.id">
                  <td>
                    <input 
                      type="checkbox" 
                      :value="item.id" 
                      :checked="bindSelectedIds.has(String(item.id))" 
                      @change="toggleOne(item)" 
                    />
                  </td>
                  <td>{{ item.spuCode || '-' }}</td>
                  <td>{{ item.productName || '-' }}</td>
                  <td>{{ item.specification || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="modal-footer">
          <span class="selected-count">已选 {{ bindSelectedIds.size }} 项</span>
          <div class="footer-buttons">
            <button @click="closeBind" class="btn-secondary">取消</button>
            <button @click="submitBind" :disabled="bindSelectedIds.size === 0" class="btn-primary">确定绑定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const loading = ref(false)
const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 查询条件
const query = reactive({
  keyword: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: null,
  supplierCode: '',
  supplierName: '',
  contactName: '',
  phone: '',
  email: '',
  address: '',
  paymentTermDays: 30,
  status: 1
})

// 对话框状态
const showDialog = ref(false)
const dialogType = ref('add')

// 产品管理相关状态
const currentSupplier = ref(null)
const products = ref([])
const showProductsPanel = ref(false)
const showBindPanel = ref(false)
const bindQuery = reactive({ keyword: '' })
const bindList = ref([])
const bindSelectedIds = ref(new Set())

// 组件挂载
onMounted(() => {
  load()
})

// 加载数据
async function load() {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    if (query.keyword) params.keyword = query.keyword
    if (query.status !== '') params.status = query.status
    
    // 构建查询字符串
    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/supplier${qs ? '?' + qs : ''}`)
    
    console.log('API响应数据:', response)
    
    // 处理不同的响应结构
    let records = []
    let totalCount = 0
    
    if (response.data) {
      // 如果响应有data字段
      records = response.data.records || response.data.list || []
      totalCount = response.data.total || 0
    } else if (response.records) {
      // 如果响应直接有records字段
      records = response.records || []
      totalCount = response.total || 0
    } else if (Array.isArray(response)) {
      // 如果响应直接是数组
      records = response
      totalCount = response.length
    }
    
    console.log('解析后的records:', records)
    console.log('解析后的total:', totalCount)
    
    list.value = records.map(r => ({ ...r, id: r.id != null ? String(r.id) : r.id }))
    total.value = totalCount
    
    console.log('处理后的数据:', list.value)
  } catch (error) {
    console.error('加载失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function search() {
  pageNum.value = 1
  load()
}

function reset() {
  query.keyword = ''
  query.status = ''
  pageNum.value = 1
  load()
}

function prevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    load()
  }
}

function nextPage() {
  if (pageNum.value * pageSize.value < total.value) {
    pageNum.value++
    load()
  }
}

function openAdd() {
  dialogType.value = 'add'
  Object.assign(form, {
    id: null,
    supplierCode: '',
    supplierName: '',
    contactName: '',
    phone: '',
    email: '',
    address: '',
    paymentTermDays: 30,
    status: 1
  })
  showDialog.value = true
}

function openEdit(item) {
  dialogType.value = 'edit'
  Object.assign(form, { ...item, id: item.id != null ? String(item.id) : item.id })
  showDialog.value = true
}

function closeDialog() {
  showDialog.value = false
}

async function submit() {
  try {
    if (!form.supplierCode || !form.supplierName || form.status === undefined) {
      alert('请填写必填项：供应商编码、供应商名称、状态')
      return
    }
    
    if (dialogType.value === 'add') {
      await apiPost('/procure-service/supplier/add', form)
    } else {
      const { supplierCode, ...updateBody } = form
      await apiPut(`/procure-service/supplier/${form.id}`, updateBody)
    }
    
    showDialog.value = false
    load()
    alert('操作成功')
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败：' + (error.message || '未知错误'))
  }
}

async function remove(item) {
  if (!confirm(`确认删除供应商"${item.supplierName}"吗？`)) return
  
  try {
    await apiDelete(`/procure-service/supplier/${item.id}`)
    load()
    alert('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败：' + (error.message || '未知错误'))
  }
}

// 产品管理功能
function openProducts(item) {
  currentSupplier.value = item
  products.value = []
  showProductsPanel.value = true
  loadSupplierProducts(item.id)
}

function closeProducts() {
  showProductsPanel.value = false
  currentSupplier.value = null
}

async function loadSupplierProducts(supplierId) {
  try {
    const data = await apiGet(`/procure-service/supplier/${supplierId}/products`)
    products.value = data.data || data || []
    console.log('供应商产品数据:', products.value)
  } catch (error) {
    console.error('加载供应商产品失败:', error)
    products.value = []
  }
}

function openBindProducts() {
  if (!currentSupplier.value) return
  showBindPanel.value = true
  bindSelectedIds.value = new Set()
  loadBindList()
}

function closeBind() {
  showBindPanel.value = false
}

async function loadBindList() {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      unboundOnly: true
    }
    if (bindQuery.keyword) params.keyword = bindQuery.keyword
    
    const qs = new URLSearchParams(params).toString()
    const data = await apiGet(`/procure-service/product${qs ? '?' + qs : ''}`)
    
    const records = data.data?.records || data.records || []
    bindList.value = records.map(r => ({ ...r, id: r.id != null ? String(r.id) : r.id }))
  } catch (error) {
    console.error('加载产品列表失败:', error)
    bindList.value = []
  }
}

function toggleAll(event) {
  const checked = event.target.checked
  if (checked) {
    bindList.value.forEach(item => bindSelectedIds.value.add(String(item.id)))
  } else {
    bindList.value.forEach(item => bindSelectedIds.value.delete(String(item.id)))
  }
}

function toggleOne(item) {
  const key = String(item.id)
  if (bindSelectedIds.value.has(key)) {
    bindSelectedIds.value.delete(key)
  } else {
    bindSelectedIds.value.add(key)
  }
}

async function submitBind() {
  if (!currentSupplier.value || bindSelectedIds.value.size === 0) return
  
  try {
    const ids = Array.from(bindSelectedIds.value).map(id => Number(id))
    await apiPost(`/procure-service/supplier/${currentSupplier.value.id}/products:bind`, { productIds: ids })
    showBindPanel.value = false
    
    // 重新加载供应商产品列表
    await loadSupplierProducts(currentSupplier.value.id)
    alert('绑定成功')
  } catch (error) {
    console.error('绑定失败:', error)
    alert('绑定失败：' + (error.message || '未知错误'))
  }
}

async function unbindProduct(product) {
  if (!confirm(`确认解绑产品"${product.productName}"吗？`)) return
  
  try {
    await apiPut(`/procure-service/product/${product.id}`, { supplierCode: null })
    
    // 重新加载产品列表
    await loadSupplierProducts(currentSupplier.value.id)
    alert('解绑成功')
  } catch (error) {
    console.error('解绑失败:', error)
    alert('解绑失败：' + (error.message || '未知错误'))
  }
}

function getStatusText(status) {
  return status === 1 ? '启用' : '禁用'
}

function getStatusClass(status) {
  return status === 1 ? 'status-enabled' : 'status-disabled'
}

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.supplier-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-group label {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
}

.form-input {
  width: 200px;
}

.form-select {
  width: 120px;
}

.btn-primary {
  padding: 8px 16px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: #3b82f6;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-secondary {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.data-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.panel-header p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.loading, .empty {
  padding: 40px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  color: #666;
  background: #f8f9fa;
  font-weight: 600;
  white-space: nowrap;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.address-cell {
  max-width: 200px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.action-cell {
  white-space: nowrap;
}

.btn-edit {
  padding: 4px 8px;
  border: 1px solid #3b82f6;
  border-radius: 4px;
  background: #fff;
  color: #3b82f6;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-edit:hover {
  background: #3b82f6;
  color: #fff;
}

.btn-delete {
  padding: 4px 8px;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  background: #fff;
  color: #f56c6c;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-delete:hover {
  background: #f56c6c;
  color: #fff;
}

.status-enabled {
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-disabled {
  color: #f56c6c;
  background: #fef0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 10px;
}

.btn-page {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-page:hover:not(:disabled) {
  background: #f8f9fa;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}

.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 600px;
  max-height: 80vh;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 8px 28px rgba(0,0,0,0.2);
  overflow: hidden;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  border: none;
  background: transparent;
  cursor: pointer;
  color: #909399;
  font-size: 18px;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-grid .full-width {
  grid-column: 1 / -1;
}

.form-grid .form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-grid .form-group label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.form-grid .form-input, .form-grid .form-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
}

.form-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  height: 80px;
  resize: vertical;
  font-size: 14px;
  font-family: inherit;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.modal-footer .btn-secondary, .modal-footer .btn-primary {
  padding: 10px 20px;
  font-size: 14px;
}

/* 产品管理对话框样式 */
.products-modal {
  width: 800px;
  max-height: 80vh;
}

.bind-modal {
  width: 800px;
  max-height: 80vh;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.products-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.products-table, .bind-table {
  max-height: 400px;
  overflow-y: auto;
}

.bind-search {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 15px;
}

.bind-search .form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bind-search .form-input {
  width: 200px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.footer-buttons {
  display: flex;
  gap: 10px;
}

.footer-buttons .btn-secondary, .footer-buttons .btn-primary {
  padding: 10px 20px;
  font-size: 14px;
}

.footer-buttons .btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
